package com.laker.autotest.webui.dev;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.laker.autotest.webui.utils.PlaywrightUtil;
import com.microsoft.playwright.*;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 增强版 Playwright 录制工具
 * 提供多种元素定位策略选择
 * 支持外部JavaScript文件管理
 *
 * @author laker
 * @version 2.1
 */
@Slf4j
public class EnhancedRecord {

    private static final String DEFAULT_URL = "https://www.baidu.com";

    private static final String ELEMENT_INSPECTOR_JS = "/static/js/element-inspector.js";
    private static final String LOCATOR_GENERATOR_JS = "/static/js/locator-generator.js";

    private static final boolean START_MAXIMIZED = true;


    public static void main(String[] args) {
        startRecording();
    }

    /**
     * 启动录制模式
     */
    private static void startRecording() {
        try (Playwright playwright = PlaywrightUtil.initPlaywright()) {
            log.info("🚀 启动 Playwright 录制工具...");

            BrowserType.LaunchOptions launchOptions = new BrowserType.LaunchOptions()
                    .setHeadless(false);

            // 构建启动参数列表
            List<String> args = CollUtil.newArrayList();

            if (START_MAXIMIZED) {
                args.add("--start-maximized");
            }

            // 自动打开 DevTools
            args.add("--auto-open-devtools-for-tabs");

            launchOptions.setArgs(args);


            try (Browser browser = playwright.chromium().launch(launchOptions)) {
                Browser.NewContextOptions contextOptions = new Browser.NewContextOptions();
                contextOptions.setViewportSize(null);
                try (BrowserContext context = browser.newContext(contextOptions);
                     Page page = context.newPage()) {

                    // 注入脚本
                    injectScripts(page);

                    // 设置监听器
                    setupListeners(page);

                    // 显示使用说明
                    printUsage();

                    // 导航到指定页面
                    log.info("🌐 导航到: {}", DEFAULT_URL);
                    page.navigate(DEFAULT_URL);

                    page.pause();
                }
            }

        } catch (Exception e) {
            log.error("❌ 启动失败", e);
            System.exit(1);
        }
    }

    /**
     * 注入JavaScript脚本
     */
    private static void injectScripts(Page page) {
        try {
            String inspectorScript = loadScript(ELEMENT_INSPECTOR_JS);
            String locatorGeneratorScript = loadScript(LOCATOR_GENERATOR_JS);

            if (CharSequenceUtil.isNotBlank(inspectorScript) &&
                    CharSequenceUtil.isNotBlank(locatorGeneratorScript)) {

                // 注入元素检查器
                page.evaluate(inspectorScript);

                // 注入定位器生成器
                page.evaluate(locatorGeneratorScript);

                log.info("✅ 脚本注入成功");
            } else {
                log.error("❌ 脚本文件加载失败");
                System.exit(1);
            }
        } catch (Exception e) {
            log.error("❌ 脚本注入失败", e);
            System.exit(1);
        }
    }

    /**
     * 加载JavaScript脚本文件
     */
    private static String loadScript(String resourcePath) {
        try (InputStream inputStream = EnhancedRecord.class.getResourceAsStream(resourcePath)) {
            if (inputStream == null) {
                log.error("❌ 找不到脚本文件: {}", resourcePath);
                return "";
            }
            return IoUtil.read(inputStream, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("❌ 读取脚本文件失败: {}", resourcePath, e);
            return "";
        }
    }

    /**
     * 设置页面监听器
     */
    private static void setupListeners(Page page) {
        // 页面加载完成时重新注入脚本
        page.onLoad(p -> {
            injectScripts(page);
            log.info("✅ 页面加载完成，脚本已重新注入");
        });

        // 监听控制台消息
        page.onConsoleMessage(msg -> {
            String text = msg.text();
            if (text.startsWith("ELEMENT_SELECTED:")) {
                String jsonData = text.substring("ELEMENT_SELECTED:".length());
                log.info("🎯 已选择元素");
                log.debug("元素信息: {}", jsonData);

                // 调用定位器生成器
                try {
                    page.evaluate("generateLocators(arguments[0])", jsonData);
                } catch (Exception e) {
                    log.warn("⚠️ 定位器生成失败: {}", e.getMessage());
                }
            } else if (text.startsWith("🎯") || text.startsWith("🔧") || text.startsWith("✅")) {
                log.info("📱 {}", text);
            }
        });

        // 监听页面错误
        page.onPageError(exception -> log.error("❌ 页面错误: {}", exception));

        // 监听请求失败
        page.onRequestFailed(request -> log.warn("⚠️ 请求失败: {}", request.url()));
    }

    /**
     * 显示使用说明
     */
    private static void printUsage() {
        log.info("🚀 Playwright 录制工具已启动！");
        log.info("==========================================");
        log.info("📖 使用说明：");
        log.info("   1. 已自动导航到百度首页");
        log.info("   2. DevTools 将自动打开");
        log.info("   3. 在控制台输入: startElementSelection()");
        log.info("   4. 点击页面元素查看定位器");
        log.info("   5. 按 ESC 键停止选择");
        log.info("");
        log.info("⚙️ 当前配置：");
        log.info("   起始URL: {}", DEFAULT_URL);
        log.info("==========================================");

    }
}